package com.requiem.hist_group_manage_springboot.service.impl;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.util.IdcardUtil;
import cn.hutool.core.util.PhoneUtil;
import com.requiem.hist_group_manage_springboot.common.HttpParamUtil;
import com.requiem.hist_group_manage_springboot.common.LogUtil;
import com.requiem.hist_group_manage_springboot.common.PageUtil;
import com.requiem.hist_group_manage_springboot.common.TimeParserUtil;
import com.requiem.hist_group_manage_springboot.constants.SystemConstants;
import com.requiem.hist_group_manage_springboot.exception.R;
import com.requiem.hist_group_manage_springboot.mapper.*;
import com.requiem.hist_group_manage_springboot.model.*;
import com.requiem.hist_group_manage_springboot.service.StudentService;
import lombok.NonNull;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
import java.util.List;
import java.util.Map;

@Service
public class StudentServiceImpl implements StudentService {


    @Autowired
    StudentMapper studentMapper;
    @Autowired
    GroupMapper groupMapper;
    @Autowired
    GroupLogMapper groupLogMapper;
    @Autowired
    DataMapper dataMapper;
    @Autowired
    ConfigsMapper configsMapper;
    @Autowired
    BlackMapper blackMapper;
    @Autowired
    HttpParamUtil httpParamUtil;
    @Autowired
    TimeParserUtil timeParserUtil;
    @Autowired
    LogUtil logUtil;
    @Autowired
    PageUtil pageUtil;
    // 过期时间（
    @Value("${cooldown.expiration}")
    private String expiration;

    @Override
    public R getList() {
        Map<String, String> params = httpParamUtil.parseQueryString();
        Map<String, Object> result = pageUtil.executePageQuery(params, () -> studentMapper.getStudentList());
        return R.success(result);
    }

    @Override
    public R getByID() {
        Map<String, String> params = httpParamUtil.parseQueryString();
        int id = Integer.parseInt(params.get("id"));

        StudentModel student = studentMapper.getStudentByID(id);
        return R.success(student);
    }

    @Override
    public R getLog() {
        Map<String, String> params = httpParamUtil.parseQueryString();
        int id = Integer.parseInt(params.get("id"));
        List<GroupLogModel> log = groupLogMapper.getLog(id, null, null);
        for (GroupLogModel groupLogModel : log) {
            String logStr = groupLogModel.getLog();
            String simpleLog = logStr.replaceAll("在.*?时", "");
            simpleLog = simpleLog.replaceAll(".*学生", "学生");
            groupLogModel.setLog(simpleLog);
        }
        return R.success(log);
    }

    @Override
    public R add(@NonNull StudentModel studentModel) {
        String studentNumber = studentModel.getStudentNumber();
        StudentModel studentNumber1 = studentMapper.getStudentExit(studentNumber);
        if (studentNumber1 != null) {
            return R.error(SystemConstants.DATA_DUPLICATE, SystemConstants.DATA_DUPLICATE_MSG);
        }
        //获取身份证号信息
        String card = studentModel.getIdCard();
        //判断身份证号是否正确
        if (!IdcardUtil.isValidCard(card) || !PhoneUtil.isPhone(studentModel.getPhone())) {
            return R.error(SystemConstants.PARAM_ERROR, SystemConstants.PARAM_SDCARD_ERROR_MSG);
        }
        IdcardUtil.Idcard sdcardInfo = IdcardUtil.getIdcardInfo(card);
        DateTime birthDate = sdcardInfo.getBirthDate();
        LocalDate localDate = birthDate.toInstant().atZone(ZoneId.systemDefault()) // 系统默认时区
                .toLocalDate();
        int age = sdcardInfo.getAge();
        Integer gender = sdcardInfo.getGender();
        if (studentModel.getAge() == null) {
            studentModel.setAge(age);
        }
        if (studentModel.getSex() == null) {
            studentModel.setSex(gender);
        }
        if (studentModel.getBirthday() == null) {
            studentModel.setBirthday(localDate);
        }
        if (studentModel.getCreateTime() == null) {
            studentModel.setCreateTime(LocalDateTime.now());
        }
        int i = studentMapper.addStudent(studentModel);
        if (i < 1) {
            return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
        }
        return R.success();
    }

    @Override
    public R delete() {
        Map<String, String> params = httpParamUtil.parseQueryString();
        int id = Integer.parseInt(params.get("id"));
        StudentModel student = studentMapper.getStudentByID(id);
        if (student == null) {
            return R.error(SystemConstants.DATA_DUPLICATE, SystemConstants.DATA_DUPLICATE_MSG);
        }
        if (student.getGroupId() != null) {
            exitGroup(student.getId(), student.getGroupId());
        }
        int i = studentMapper.deleteStudent(id);
        if (i < 1) {
            return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
        }
        blackMapper.delete(id);
        return R.success();
    }

    @Override
    public R edit(@NonNull StudentModel studentModel) {
        StudentModel student = studentMapper.getStudentByID(studentModel.getId());
        if (student == null) {
            return R.error(SystemConstants.DATA_DUPLICATE, SystemConstants.DATA_DUPLICATE_MSG);
        }
        //获取身份证号信息
        String card = studentModel.getIdCard();
        //判断身份证号是否正确
        if (card != null) {
            if (!IdcardUtil.isValidCard(card) || !PhoneUtil.isPhone(studentModel.getPhone())) {
                return R.error(SystemConstants.PARAM_ERROR, SystemConstants.PARAM_SDCARD_ERROR_MSG);
            }
            IdcardUtil.Idcard sdcardInfo = IdcardUtil.getIdcardInfo(card);
            DateTime birthDate = sdcardInfo.getBirthDate();
            LocalDate localDate = birthDate.toInstant().atZone(ZoneId.systemDefault()) // 系统默认时区
                    .toLocalDate();
            int age = sdcardInfo.getAge();
            Integer gender = sdcardInfo.getGender();
            studentModel.setAge(age);
            studentModel.setSex(gender);
            studentModel.setBirthday(localDate);
        }

        int i = studentMapper.editStudent(studentModel);
        if (i < 1) {
            return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
        }
        return R.success();
    }

    @Override
    public R joinGroup(int studentId, int groupId) {
        //判断数据
        Integer logType = groupLogMapper.getGroupTypeByID(studentId, groupId);
        if (logType != null && logType == 1) {
            return R.error(SystemConstants.DATA_DUPLICATE, SystemConstants.DATA_DUPLICATE_GROUP_MSG);
        }
        //判断是否被拉黑
        BlackModel byID = blackMapper.getByID(studentId);
        if (byID != null) {
            return R.error(SystemConstants.FORBIDDEN, SystemConstants.FORBIDDEN_JOIN_MSG);
        }
        //判断是否有冷却期
        LocalDateTime expiresByID = dataMapper.getExpiresByID(studentId);
        if (expiresByID != null) {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime formattedTime = now.truncatedTo(ChronoUnit.SECONDS);
            if (formattedTime.isBefore(expiresByID)) {
                Duration duration = Duration.between(formattedTime, expiresByID);
                // 提取时、分、秒
                long hours = duration.toHours();
                long minutes = duration.toMinutes() % 60; // 取余避免超过60分钟
                long seconds = duration.getSeconds() % 60; // 取余避免超过60秒
                String readableDuration = String.format("%d小时%d分钟%d秒", hours, minutes, seconds);
                return R.error(SystemConstants.FORBIDDEN, SystemConstants.FORBIDDEN_JOIN_EXPIRES_MSG + readableDuration + "后可重新申请");
            }
        }
        //小组人数加一，热度加一
        GroupModel group = groupMapper.getGroupByID(groupId);
        if (group == null) {
            return R.error(SystemConstants.DATA_DUPLICATE, SystemConstants.DATA_DUPLICATE_MSG);
        }
        if (group.getHot() == null) {
            group.setHot(0);
        }
        if (group.getNumber() == null) {
            group.setNumber(0);
        }
        if (logType == null) {
            group.setHot(group.getHot() + 1);
        }
        group.setNumber(group.getNumber() + 1);
        int i = groupMapper.editGroup(group);
        if (i < 1) {
            return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
        }
        return logUtil.recordStudent(studentId, groupId, SystemConstants.JOIN_GROUP);
    }

    @Override
    public R exitGroup(int studentId, int groupId) {
        //判断数据
        Integer logType = groupLogMapper.getGroupTypeByID(studentId, groupId);
        if (logType == null) {
            return R.error(SystemConstants.DATA_DUPLICATE, SystemConstants.DATA_DUPLICATE_EXITGROUP_MSG);
        }
        if (logType != 1) {
            return R.error(SystemConstants.DATA_DUPLICATE, SystemConstants.DATA_DUPLICATE_EXITGROUP_MSG);
        }

        //读取配置
        long expires = configsMapper.getExpires();
        long expiresMillis;
        if (expires == 0) {
            expiresMillis = timeParserUtil.parseToMillis(expiration);
        } else {
            expiresMillis = expires;
        }
        //设置过期时间
        DataModel dataModel = new DataModel();
        LocalDateTime now = LocalDateTime.now();
        LocalDateTime formattedTime = now.truncatedTo(ChronoUnit.SECONDS);
        LocalDateTime expireTimeA = formattedTime.plus(Duration.ofMillis(expiresMillis));
        dataModel.setStudentId(studentId);
        dataModel.setExpires(expireTimeA);
        dataModel.setCreateTime(formattedTime);
        LocalDateTime expiresByID = dataMapper.getExpiresByID(studentId);
        int add;
        if (expiresByID == null) {
            add = dataMapper.add(dataModel);
        } else {
            add = dataMapper.edit(dataModel);
        }
        if (add < 1) {
            return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
        }
        //小组人数减一
        GroupModel group = groupMapper.getGroupByID(groupId);
        if (group == null) {
            return R.error(SystemConstants.DATA_DUPLICATE, SystemConstants.DATA_DUPLICATE_MSG);
        }
        group.setNumber(group.getNumber() - 1);
        int i = groupMapper.editGroup(group);
        if (i < 1) {
            return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
        }
        //记录日志
        return logUtil.recordStudent(studentId, groupId, SystemConstants.EXIT_GROUP);
    }

    @Override
    public R SearchList(StudentModel studentModel) {
        Map<String, String> params = httpParamUtil.parseQueryString();
        Map<String, Object> result = pageUtil.executePageQuery(params, () -> studentMapper.getSearchList(studentModel));
        return R.success(result);
    }

    /*
     * 评论功能
     */
    @Override
    public R getTeacher(int groupId) {
        List<TeacherModel> teacher = studentMapper.getTeacher(groupId);
        return R.success(teacher);
    }

    @Override
    public R getEvaluation(int studentId) {
        List<EvaluationModel> evaluations = studentMapper.getEvaluation(studentId);

        for (EvaluationModel evaluationModel : evaluations) {
            if (evaluationModel.getEvaluation() == null) {
                continue;
            }
            String[] parts = evaluationModel.getEvaluation().split("\\|", 3);
            // 确保分割后有足够的部分
            if (parts.length >= 3) {
                if (evaluationModel.getStudentName() == null) {
                    evaluationModel.setStudentName(parts[0]);
                }
                if (evaluationModel.getTeacherName() == null) {
                    evaluationModel.setTeacherName(parts[1]);
                }
                evaluationModel.setEvaluation(parts[2]);
            }
        }
        return R.success(evaluations);
    }

    @Override
    public R addEvaluation(EvaluationModel evaluationModel) {
        evaluationModel.setType(SystemConstants.STUDENT_EVALUATION);
        evaluationModel.setCreateTime(LocalDateTime.now());
        String evaluationStr = String.join("|", evaluationModel.getStudentName(), evaluationModel.getTeacherName(), evaluationModel.getEvaluation());

        evaluationModel.setEvaluation(evaluationStr);
        int i = studentMapper.addEvaluation(evaluationModel);
        if (i < 1) {
            return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
        }
        return R.success();
    }

    @Override
    public R resetPassword(int id, String password) {
        if (id == 0 || password == null) {
            return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
        }
        String finalPassword = DigestUtils.md5DigestAsHex(password.getBytes());
        int i = studentMapper.resetPassword(id, finalPassword);
        if (i < 1) {
            return R.error(SystemConstants.ERROR_CODE, SystemConstants.ERROR_MSG);
        }
        return R.success();
    }

}
